<template>
  <div class="login-container">
    <div class="login-container bg-wrapper" >
      <el-card class="login-card" shadow="always">
        <div class="system-header">
          <img src="../assets/logo.png" class="system-logo" alt="医疗系统logo">
          <h1 class="system-title">智慧医疗管理系统</h1>
        </div>
        <el-form ref="loginFormRef" label-width="80px" :model="loginForm" :rules="rules">
          <!-- 用户输入 -->
          <el-form-item label="用户" prop="username">
            <el-input
                placeholder="请输入用户名或手机号"
                v-model="loginForm.username"
                clearable
            ></el-input>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item label="密码" prop="password">
            <el-input
                type="password"
                placeholder="请输入密码"
                show-password
                v-model="loginForm.password"
                clearable
            ></el-input>
          </el-form-item>

          <!-- 角色选择 -->
          <el-form-item label="类型" prop="role">
            <el-select v-model="loginForm.role" placeholder="请选择" style="width:100%">
              <el-option label="患者" value="patient"></el-option>
              <el-option label="医师/审核员" value="doctor"></el-option>
              <el-option label="管理员" value="admin"></el-option>
            </el-select>
          </el-form-item>

          <!-- 登录/注册按钮 -->
          <el-form-item class="button-group">
            <el-button type="primary" @click="login" :class="{'single-button': loginForm.role !== 'patient'}">登录</el-button>
            <el-button v-if="loginForm.role === 'patient'" @click="register">注册</el-button>
          </el-form-item>

          <!-- 添加忘记密码链接 -->
          <div class="forgot-password-wrapper">
            <el-link type="primary" @click="goToForgotPassword">已有账号，忘记密码？</el-link>
          </div>

          <!-- 协议条款 -->
          <el-form-item class="agreement-item">
            <el-checkbox v-model="agreeToTerms">我已阅读并同意</el-checkbox>
            <el-link type="primary" @click="showTermsDialog">《用户服务协议》</el-link>
            <span>和</span>
            <el-link type="primary" @click="showPrivacyDialog">《隐私政策》</el-link>
          </el-form-item>

          <!-- 第三方登录区域 - 仅在角色为患者时显示 -->
          <div v-if="loginForm.role === 'patient'" class="third-party-login">
            <div class="login-divider">
              <span class="divider-line"></span>
              <span class="divider-text">第三方登录</span>
              <span class="divider-line"></span>
            </div>
            <div class="login-buttons">
              <el-button circle class="third-party-button" @click="wechatLogin">
                <img src="../assets/wechat.svg" class="login-icon" alt="微信登录">
              </el-button>
              <el-button circle class="third-party-button" @click="phoneLogin">
                <img src="../assets/phone.svg" class="login-icon" alt="手机号登录">
              </el-button>
              <el-button circle class="third-party-button" @click="emailLogin">
                <img src="../assets/email.svg" class="login-icon" alt="邮箱登录">
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, watch} from "vue";
import {ElMessage} from 'element-plus'
import axios from "axios";
import {useRouter} from 'vue-router'

const agreeToTerms = ref(false);
const router = useRouter()
const loginCardRef = ref(null)
// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
  role: ""
})
// 表单引用
const loginFormRef = ref(null)

// 登录函数
function login() {
  // 1. 先进行表单验证
  loginFormRef.value.validate((valid) => {
    if (!valid) return; // 表单验证不通过直接返回

    // 2. 表单验证通过后，检查协议是否勾选
    if (!agreeToTerms.value) {
      ElMessage.error({
        message: '请同意用户协议',
        type: 'error',
        duration: 2000,
        customClass: 'agreement-error-message'
      });
      return;
    }

    // 3. 协议已勾选，执行登录请求
    axios({
      method: 'post',
      url: 'http://localhost:6063/views/login',
      data: JSON.stringify( {
        username: loginForm.username,
        password: loginForm.password,
        role: loginForm.role
      }),
      headers: { // 修复3: 添加JSON内容类型头
        'content-Type': 'application/json'
      },
      withCredentials: false
    }).then(function (response) {
      console.log('完整响应', response)
      let data = response.data;
      if (data.code === 200) {
        console.log('登录成功，准备跳转')
        localStorage.setItem("username", loginForm.username)
        localStorage.setItem("role", loginForm.role)
        // 4.跳转到相应页面
        switch (loginForm.role) {
          case 'patient':
            router.push('/Patient')
            break
          case 'doctor':
            router.push('/Doctor')
            break
          case 'admin':
            router.push('/Admin')
            break
          default:
            router.push('/home')
        }
      } else if (data.code === 1001) {
        console.log('登录失败', data.message)
        ElMessage.error(data.message)
      }
    }).catch(function (error) {
      console.log('请求错误', error)
      ElMessage.error(error)
    })
  })
}

function goToForgotPassword() {
  router.push("/forgot-password")
}

// 显示协议弹窗
function showTermsDialog() {
  console.log('显示用户服务协议');
}

function showPrivacyDialog() {
  console.log('显示隐私政策');
}

// 注册函数
function register() {
  router.push("/register")
}

// 第三方登录函数 - 简化版，只进行页面跳转
function wechatLogin() {
  router.push("/wechat-login")
}

function phoneLogin() {
  router.push("/phone-login")
}

function emailLogin() {
  router.push("/email-login")
}

// 表单验证规则
const rules = {
  username: [
    {required: true, message: "请输入用户名或手机号", trigger: 'blur'},
    {min: 3, max: 15, message: '长度应在3-15个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, message: "请输入密码", trigger: 'blur'},
    {min: 6, max: 20, message: '长度应在6-20个字符之间', trigger: 'blur'}
  ],
  role: [{required: true, message: "请选择角色类型", trigger: 'change'}]
}

// 切换角色时清空表单
watch(
    () => loginForm.role,
    () => {
      loginForm.username = ''
      loginForm.password = ''
      agreeToTerms.value = false
    }
)
</script>

<style scoped>
/* 第三方登录样式 */
.third-party-login {
  margin-top: 25px;
}

.login-divider {
  display: flex;
  align-items: center;
  margin: 15px 0;
  color: #909399;
}

.divider-line {
  flex: 1;
  height: 1px;
  background: #dcdfe6;
}

.divider-text {
  padding: 0 15px;
  font-size: 14px;
}

.login-buttons {
  display: flex;
  justify-content: space-around;
  padding: 0 30px;
}

.third-party-button {
  width: 44px;
  height: 44px;
  padding: 0;
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.third-party-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

/* 背景样式 */
.bg-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('../assets/lgbg.png') no-repeat center center;
  background-size: cover;
  transform-origin: center center; /* 关键：从中心缩放 */
  transition: transform 0.3s ease; /* 加入过渡动画 */
  z-index: -1;
}

/* 登录容器样式 */
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 500px; /* 初始宽度 */
  min-height: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.system-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
}

.system-logo {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.system-title {
  font-size: 22px;
  color: #409EFF;
  margin: 0;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.button-group .el-button {
  flex: 1;
  margin: 0;
}

.button-group .el-button:not(first-child) {
  margin-left: 10px;
}

.button-group.el-button:only-child {
  flex: none;
  width: 50%;
  margin: 0 auto;
}

/* 协议条款样式 */
.agreement-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

/* 错误提示样式 */
:deep(.agreement-error-message) {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fde2e2;
}

/*忘记密码样式*/
.forgot-password-wrapper {
  display: flex;
  justify-content: center;
  margin-top: -10px;
  margin-bottom: 10px;
  width: 100%;
}

.forgot-password-wrapper .el-link {
  font-size: 14px;
}
</style>
